<template>
	<view class="shop-page">
		<uv-toast ref="toast"></uv-toast>
		<PLoader :loading="globalLoading" background-color="#00000060"></PLoader>
		<!-- 顶部搜索栏 -->
		<view class="search-bar">
			<uv-input placeholder="搜索店铺名称" prefixIcon="search" prefixIconStyle="font-size: 24px;color: #999"
				v-model="searchKey" shape="circle"
				:customStyle="{ background: '#f0f0f0', fontSize: '28rpx', color: '#333' }" @confirm="onSearch"
				confirmType="search" :disabled="loading">
				<!-- 添加搜索按钮 -->
				<template #suffix>
					<view class="search-btn" @tap="onSearch" :class="{ 'loading': loading }">
						<uv-loading-icon v-if="loading" size="26" mode="circle" color="#ffffff"></uv-loading-icon>
						<text v-else>搜索</text>
					</view>
				</template>
			</uv-input>
			
			
			<!-- 分类筛选 -->
			<view class="filter-bar">
				<view v-for="(item, index) in filterList" :key="index" class="filter-item"
					:class="{ active: currentFilter === item.type }" @click="changeFilter(item.type)">
					<text>{{ item.name }}</text>
					<text class="sort-icon" v-if="item.sort">{{ item.sort === 'asc' ? '↑' : '↓' }}</text>
				</view>
			</view>
		</view>

		<view class="empty" v-if="!shopList || shopList.length === 0">
			<uv-empty textColor="#8094b9" textSize="28" iconColor="#8094b9" iconSize="100" text="暂无附近10km门店"></uv-empty>
		</view>

		<!-- 店铺列表 -->
		<scroll-view scroll-y class="shop-list" @scrolltolower="onReachBottom">
			<view v-for="shop in shopList" :key="shop.id" class="shop-item" @tap="goToMerchantDetail(shop.id)">
				<image :src="shop.image || '/static/default-shop.png'" class="shop-image"></image>
				<view class="shop-info">
					<view class="shop-header">
						<text class="shop-name">{{ shop.name }}</text>
						<text class="distance">{{ shop.distance }}km</text>
					</view>
					<view class="merchant-name">{{ shop.merchantName }}</view>
					<view class="des" v-if="shop.des">
						{{ shop.des }}
					</view>
					<view class="bottom-info">
						<text class="opening-hours">营业时间: {{ shop.openingHours }}</text>
						<text class="status" :class="shop.status ? 'active' : ''">
							{{ shop.status ? '营业中' : '已关闭' }}
						</text>
					</view>
				</view>
			</view>
			<view class="loading-more" v-if="shopList.length > 0">
				<uv-loadmore :status="loading ? 'loading' : (hasMore ? 'loadmore' : 'nomore')"></uv-loadmore>
			</view>
		</scroll-view>

		<CustomTabBar selected="2" />
	</view>
</template>

<script>
	import debounce from '@/uni_modules/uv-ui-tools/libs/function/debounce.js';
	export default {
		data() {
			return {
				searchKey: '',
				currentFilter: 'time',
				filterList: [{
						name: '最新入驻',
						type: 'time',
						sort: 'desc'
					},
					{
						name: '24小时营业',
						type: '24h'
					},
					{
						name: '距离优先',
						type: 'distance',
						sort: 'asc'
					}
				],
				shopList: [],
				pageParams: {
					current: 1,
					size: 10
				},
				location: {
					latitude: '',
					longitude: ''
				},
				loading: false,
				hasMore: true,
				// 添加默认表单状态
				defaultForm: {
					searchKey: '',
					currentFilter: 'time',
					pageParams: {
						current: 1,
						size: 10
					}
				},
				globalLoading: false, // 添加全局loading状态
				hasLocation: false, // 添加定位状态标记
			}
		},
		onLoad() {
			this.getLocation();
		},
		methods: {
			showToast(msg, type = 'default', duration = 2000) {
				this.$refs.toast.show({
					message: msg,
					type: type,
					duration: duration,
				})
			},
			async getLocation() {
				this.globalLoading = true;
				try {
					const location = await uni.getLocation({
						type: 'gcj02'
					});
					this.location.latitude = location.latitude.toString();
					this.location.longitude = location.longitude.toString();
					this.hasLocation = true; // 标记已获取到定位
					await this.fetchShopList();
				} catch (e) {
					this.showToast('获取定位信息失败', 'default', 1000);
					this.hasLocation = false;
				} finally {
					this.globalLoading = false;
				}
			},
			async fetchShopList(reset = false) {
				// 如果没有定位信息，重新获取定位
				if (!this.hasLocation) {
					await this.getLocation();
					return;
				}

				if (reset) {
					this.pageParams.current = 1;
					this.hasMore = true;
					this.shopList = [];
				}
				if (!this.hasMore || this.loading) return;
				this.loading = true;
				try {
					const params = {
						name: this.searchKey,
						...this.pageParams,
						...this.location,
						settledTime: this.currentFilter === 'time' ? 1 : null,
						is24Hour: this.currentFilter === '24h' ? true : null
					};
					const res = await this.$http.post('/merchant/near/list', params);
					if (res.items) {
						if (reset) {
							this.shopList = res.items;
						} else {
							this.shopList = [...this.shopList, ...res.items];
						}
						this.hasMore = this.shopList.length < res.count;
						if (this.hasMore) {
							this.pageParams.current++;
						}
					}
				} catch (e) {
					console.error(e);
					this.showToast('获取商户列表失败', 'error', 1000);
				} finally {
					this.loading = false;
				}
			},
			async changeFilter(type) {
				if (this.currentFilter === type || this.loading) return;
				this.currentFilter = type;
				await this.fetchShopList(true);
			},
			goToMerchantDetail(merchantId) {
				uni.navigateTo({
					url: `/subpkg/merchant_detail/merchant_detail?merchantId=${merchantId}`
				})
			},
			// 搜索方法
			onSearch() {
				if (this.loading) return;
				debounce(() => {
					this.fetchShopList(true);
				}, 300);
			},
			// 重置表单
			resetForm() {
				this.searchKey = this.defaultForm.searchKey;
				this.currentFilter = this.defaultForm.currentFilter;
				this.pageParams = {
					...this.defaultForm.pageParams
				};
				this.shopList = [];
				this.hasMore = true;
				this.hasLocation = false; // 重置定位状态
			}
		},
		onPullDownRefresh() {
			this.fetchShopList(true).then(() => {
				uni.stopPullDownRefresh();
			});
		},
		onReachBottom() {
			if (this.hasMore) {
				this.fetchShopList();
			}
		},
		onShow() {
			this.getLocation();
			this.fetchShopList();
		},
		// 页面隐藏时
		onHide() {
			// 页面隐藏时重置表单
			this.resetForm();
		},
		// 页面卸载时
		onUnload() {
			// 页面卸载时重置表单
			this.resetForm();
		}
	}
</script>

<style lang="scss" scoped>
	@import './function.scss';

	.shop-item {
		// 添加点击反馈效果
		transition: transform 0.2s ease;

		&:active {
			transform: scale(0.98);
		}
	}

	// 添加搜索按钮样式
	.search-bar {
		.search-btn {
			height: 56rpx;
			padding: 0 24rpx;
			background: #ff5722;
			border-radius: 28rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-left: 16rpx;
			min-width: 100rpx; // 添加最小宽度，防止loading时抖动

			text {
				color: #fff;
				font-size: 26rpx;
			}

			&.loading {
				opacity: 0.8;
				pointer-events: none; // 加载时禁止点击
			}

			&:active {
				opacity: 0.8;
			}
		}
	}
</style>